package com.xg.frame.shiro;

import io.jsonwebtoken.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * JWT工具类
 * @author dehuisun
 *
 */
@Slf4j
@ConfigurationProperties(prefix = "xg.jwt")
@Component
@Data
public class JwtUtil {

    private static String secret;
    public static long expire;

    /**
     * 生成jwt token
     */
    public static String sign(String userId) {
        //过期时间
        Date expireDate = new Date(System.currentTimeMillis() + expire * 1000);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(userId)
                .setIssuedAt(new Date())
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 校验token
     */
    public static boolean verify(String token) {
        try {
            Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 获取userId
     */
    public static String getUserId(String token) {
        try {
            Claims claims=Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
            return claims.getSubject();
        }catch (ExpiredJwtException e){
            Claims claims = e.getClaims();
            return claims.getSubject();
        }catch (Exception e){
            return null;
        }
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        JwtUtil.secret = secret;
    }

    public long getExpire() {
        return expire;
    }

    public void setExpire(long expire) {
        JwtUtil.expire = expire;
    }

}
